package cn.itcast.goods.category.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.sun.org.apache.bcel.internal.generic.NEW;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.category.doamin.Category;
import cn.itcast.jdbc.TxQueryRunner;

/**
 * 分类模块持久层
 * @author GiantTao
 *
 */
public class CategoryDao {
	QueryRunner qr=new TxQueryRunner();
	
	/**
	 * 把一个Map中的数据映射到Category中
	 */
	private Category toCategoty(Map<String,Object> map ){
		Category category = CommonUtils.toBean(map, Category.class);
		String pid=(String)map.get("pid");
		if(pid!=null){
			/**
			 * 如果pid不为空，使用一个父分类对象来存储pid的值
			 * 再把该父分类对象付给category
			 */
			Category parent=new Category();
			parent.setCid(pid);
			category.setParent(parent);
		}
		return category;
	}

	/**
	 * 可以把多个Map<String，Object>(List<Map>)映射成多个Category(List<Category>)
	 * @param mapList
	 * @return
	 */
	private List<Category> toCategoryList(List<Map<String, Object>> mapList){
		List<Category> categoryList=new ArrayList<Category>();
		for(Map<String, Object> map:mapList){
			Category category=toCategoty(map);
			categoryList.add(category);
		}
		return categoryList;
	}

	/**
	 * 查询所有分类
	 * @return
	 * @throws SQLException
	 */
	public List<Category> findAll() throws SQLException{
		/**
		 * 1.查询所有一级分类
		 */
		String sql="select * from t_category where pid is null";
		List<Map<String, Object>> mapList=qr.query(sql, new MapListHandler());
		List<Category> parents=toCategoryList(mapList);
		/**
		 * 2.遍历所有一级分类，为每一个一级分类加载它的二级分类
		 */
		for(Category parent:parents){
			//查询当前父分类的所有子分类
			List<Category> children=findByParent(parent.getCid());
			//将子分类设置给父分类
			parent.setChildren(children);
		}
		return parents;
		
	}
	/**
	 * 通过父分类查找子分类
	 * @throws SQLException 
	 */
	private List<Category> findByParent(String pid) throws SQLException {
		String sql="select * from t_category where pid=?";
		List<Map<String, Object>> mapList=qr.query(sql, new MapListHandler(),pid);
		return toCategoryList(mapList);
	}
	
}
